<?php

$app->HandleFunc("/api",function() {
	$config = [];
	$req = $_REQUEST;

  $createSign = function ($cmd,$param,$time,$appid,$appserct){
      $sign = strtoupper( sha1( $cmd.$param.$time.$appserct));
      return $sign;
  };

  //接收参数与赋值
  $cmd = $req['cmd'];
  $param = $req['param'];
  $timestamp = $req['timestamp'];
  $sign = $req['sign'];
  $appid = $req['appid'];
  
  
  //参数数量不全
  if($cmd == "" || $param == "" || $timestamp == "" || $sign == "" || $appid == ""){
    $err = ["非法请求"];
    $this->ServerJson($err);
    return true;
  }

 

  //获取接口配置文件
  $apiModel = new Api_model($this);
  $apiEntity = $apiModel->getApiEntity($cmd);
  $appserct = $apiModel->getAppsecret($appid);

  if($apiEntity == "" || $apiEntity == false){
    $err = ["接口不存在"];
    $this->ServerJson($err);
    return true;
  }

  //计算签名
  $calSign = $createSign($cmd,$param,$timestamp,$appid,$appserct);
  //签名校验
  if($apiEntity['sign'] == 0 && $calSign != $sign){
    $err = ["签名错误"];
    $this->ServerJson($err);
    return true;
  }

  
  //防止重复请求
  if($apiEntity['frequency'] == 1){
    $request = [$cmd,$param,$timestamp,$sign,$appid,$calSign];
    $reqKey = md5(json_encode($request));
    //判断timestamp时间，超过10分钟则为超时
    if( time() - $timestamp > 10*60 ){
      $err = ["请求超时"];
      $this->ServerJson($err);
      return true;
    }
    //从redis中读取该key ，如果存在则为重复请求
    $reqExist = $this->redis->exists($reqKey);
    if($reqExist){
      $err = ["重复请求"];
      $this->ServerJson($err);
      return true;
    }else{
      //将key存入redis，存活时间为11分钟
      $this->redis->setex($reqKey,11*60,"request:".date('Y-m-d H:i:s',time()));
    }
  }

  //实例化接口处理类
  $path = __DIR__."/../libs".$apiEntity['classpath'].".php";

  if(file_exists($path)){
      include_once $path;
  }else{
      $mock = $apiEntity['mock'];
      $this->ServerJson($mock);
      return true;
  }

  $actor = new $cmd($this);

  $paramObj = json_decode(base64_decode($param));

  $ret = $actor->run($paramObj); 

  if($ret == false || $ret == "" || !is_array($ret)){
    $ret = ["系统繁忙"];
  }

  $this->ServerJson($ret);
});

